import 'package:sqflite/sqflite.dart';

/// 相册上传进度记录模型
/// 用于存储每个相册的上传进度，支持断点续传
class UploadProgressRecord {
  int? id; // 数据库主键
  String albumId; // 相册ID
  String albumName; // 相册名称
  int processedCount; // 已处理的资产数量
  String? lastAssetId; // 最后处理的资产ID
  int updateTime; // 更新时间戳（毫秒）
  bool isCompleted; // 是否已完成上传

  /// 构造函数
  UploadProgressRecord({
    this.id,
    required this.albumId,
    required this.albumName,
    this.processedCount = 0,
    this.lastAssetId,
    int? updateTime,
    this.isCompleted = false,
  }) : updateTime = updateTime ?? DateTime.now().millisecondsSinceEpoch;

  /// 从Map创建进度记录对象（用于数据库查询）
  factory UploadProgressRecord.fromMap(Map<String, dynamic> map) {
    return UploadProgressRecord(
      id: map['id'] as int,
      albumId: map['album_id'] as String,
      albumName: map['album_name'] as String,
      processedCount: map['processed_count'] as int,
      lastAssetId: map['last_asset_id'] as String?,
      updateTime: map['update_time'] as int,
      isCompleted: (map['is_completed'] as int) == 1,
    );
  }

  /// 转换为Map（用于数据库插入或更新）
  Map<String, dynamic> toMap() {
    return {
      if (id != null) 'id': id,
      'album_id': albumId,
      'album_name': albumName,
      'processed_count': processedCount,
      'last_asset_id': lastAssetId,
      'update_time': updateTime,
      'is_completed': isCompleted ? 1 : 0,
    };
  }

  /// 创建数据库表
  static Future<void> createTable(Database db) async {
    await db.execute('''
      CREATE TABLE IF NOT EXISTS upload_progress_records (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        album_id TEXT NOT NULL UNIQUE,
        album_name TEXT NOT NULL,
        processed_count INTEGER NOT NULL DEFAULT 0,
        last_asset_id TEXT,
        update_time INTEGER NOT NULL,
        is_completed INTEGER NOT NULL DEFAULT 0
      )
    ''');

    // 创建索引以加速查询
    await db.execute(
      'CREATE INDEX IF NOT EXISTS idx_album_id ON upload_progress_records (album_id)',
    );
    await db.execute(
      'CREATE INDEX IF NOT EXISTS idx_completed ON upload_progress_records (is_completed)',
    );
  }

  /// 更新上传进度
  void updateProgress(int newCount, String? assetId) {
    processedCount = newCount;
    lastAssetId = assetId;
    updateTime = DateTime.now().millisecondsSinceEpoch;
  }

  /// 标记为已完成
  void markAsCompleted() {
    isCompleted = true;
    updateTime = DateTime.now().millisecondsSinceEpoch;
  }

  @override
  String toString() {
    return 'UploadProgressRecord{id: $id, albumId: $albumId, albumName: $albumName, processedCount: $processedCount, isCompleted: $isCompleted}';
  }
}
